package handlers

import (
	"encoding/json"
	"fmt"
	// "log"
	"net/http"
	"shopback/models"
	"strconv"

	"github.com/gorilla/mux"
)

// AddToCart 向购物车中添加商品
	// @Summary 向购物车中添加商品
	// @Description 根据用户ID、商品ID和数量向购物车添加商品
	// @Tags 购物车
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Param cart_item body models.CartItem true "商品信息"
	// @Success 200 {string} string "商品添加成功"
	// @Failure 400 {string} string "无效的请求参数"
	// @Failure 404 {string} string "购物车未找到"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /carts/{user_id}/items [post]
func AddToCart(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userID, err := strconv.Atoi(vars["user_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的用户ID"}`, http.StatusBadRequest)
		return
	}

	// 解析请求体中的商品信息
	var cartItem models.CartItem
	if err := json.NewDecoder(r.Body).Decode(&cartItem); err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的请求参数"}`, http.StatusBadRequest)
		return
	}

	// 校验商品ID和数量
	if cartItem.ProductID == 0 || cartItem.Quantity <= 0 {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的商品ID或数量"}`, http.StatusBadRequest)
		return
	}

	// 调用模型层的 AddToCart 函数来添加商品到购物车
	cartID, err := models.AddToCart(userID, cartItem.ProductID, cartItem.Quantity)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, fmt.Sprintf(`{"message": "%s"}`, err.Error()), http.StatusInternalServerError)
		return
	}

	// 返回成功消息
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"message": "商品加入购物车成功",
		"cart_id": cartID,
	})
}

// GetCart 获取指定用户的购物车信息
	// @Summary 获取用户购物车信息
	// @Description 根据用户ID获取购物车信息和商品
	// @Tags 购物车
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Success 200 {object} models.Cart "购物车信息"
	// @Failure 400 {string} string "无效的用户ID"
	// @Failure 404 {string} string "购物车未找到"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /carts/{user_id} [get]
func GetCart(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userID, err := strconv.Atoi(vars["user_id"])
	if err != nil {
		http.Error(w, `{"message": "无效的用户ID"}`, http.StatusBadRequest)
		return
	}

	// 获取购物车信息
	cart, cartItems, err := models.GetCartByUserID(userID)
	if err != nil {
		http.Error(w, `{"message": "获取购物车失败"}`, http.StatusInternalServerError)
		return
	}

	// 如果购物车为空，返回空购物车
	if cart.UserID == 0 {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]interface{}{
			"cart":       models.Cart{UserID: userID},
			"cart_items": []models.CartItem{},
		})
		return
	}

	// 返回购物车信息
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"cart":       cart,
		"cart_items": cartItems,
	})
}

// UpdateCartItem 更新购物车中商品的数量
	// @Summary 更新购物车商品数量
	// @Description 更新购物车中指定商品的数量
	// @Tags 购物车
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Param product_id path int true "商品ID"
	// @Param cart_item body models.CartItem true "更新的商品信息"
	// @Success 200 {string} string "数量更新成功"
	// @Failure 400 {string} string "无效的请求参数"
	// @Failure 404 {string} string "商品未找到"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /carts/{user_id}/items/{product_id} [put]
func UpdateCartItem(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userID, err := strconv.Atoi(vars["user_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的用户ID"}`, http.StatusBadRequest)
		return
	}

	productID, err := strconv.Atoi(vars["product_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的商品ID"}`, http.StatusBadRequest)
		return
	}

	// 解析请求体
	var cartItem models.CartItem
	if err := json.NewDecoder(r.Body).Decode(&cartItem); err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的请求参数"}`, http.StatusBadRequest)
		return
	}

	// 验证商品数量
	if cartItem.Quantity <= 0 {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "商品数量必须大于0"}`, http.StatusBadRequest)
		return
	}

	// 更新购物车商品数量
	err = models.UpdateCartItemQuantity(userID, productID, cartItem.Quantity)
	if err != nil {
		// 根据错误类型返回不同的状态码
		if err.Error() == "商品不存在" {
			w.Header().Set("Content-Type", "application/json")
			http.Error(w, `{"message": "商品不存在"}`, http.StatusNotFound)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		http.Error(w, fmt.Sprintf(`{"message": "%s"}`, err.Error()), http.StatusInternalServerError)
		return
	}

	// 返回成功消息
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{
		"message": "数量更新成功",
	})
}

// DeleteFromCart 从购物车中删除指定商品
	// @Summary 从购物车中删除商品
	// @Description 根据用户ID和商品ID从购物车中删除指定商品
	// @Tags 购物车
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Param product_id path int true "商品ID"
	// @Success 200 {string} string "商品删除成功"
	// @Failure 400 {string} string "无效的请求参数"
	// @Failure 404 {string} string "商品未找到"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /carts/{user_id}/items/{product_id} [delete]
func DeleteFromCart(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userID, err := strconv.Atoi(vars["user_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的用户ID"}`, http.StatusBadRequest)
		return
	}

	productID, err := strconv.Atoi(vars["product_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的商品ID"}`, http.StatusBadRequest)
		return
	}

	// 调用模型层的 DeleteFromCart 函数来从购物车中删除商品
	rowsAffected, err := models.DeleteFromCart(userID, productID)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, fmt.Sprintf(`{"message": "%s"}`, err.Error()), http.StatusInternalServerError)
		return
	}

	if rowsAffected == 0 {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "商品未找到"}`, http.StatusNotFound)
		return
	}

	// 返回成功消息
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{
		"message": "商品删除成功",
	})
}